﻿using System.Collections.Generic;
using System.Web.Http;
using ESoft.Core.Common.Util;
using ESoft.Core.Jwt;
using ESoft.Core.Jwt.Model;
using ESoft.Core.Logging;

namespace ESoft.API.Api
{
    [RoutePrefix("api/auth")]
    [AllowAnonymous]
    public class AuthController : ApiController
    {
        private readonly ILogger logger = LogManager.GetLogger(typeof(AuthController));

        public LoginResult Post(LoginRequest request)
        {
            logger.Info(JsonUtil.serialize(request));
            LoginResult rs = new LoginResult();
            if (request.UserName == "admin" && request.Password == "123")
            {
                //如果用户登录成功，则可以得到该用户的身份数据。当然实际开发中，这里需要在数据库中获得该用户的角色及权限
                AuthInfo authInfo = new AuthInfo
                {
                    IsAdmin = true,
                    Roles = new List<string> { "admin", "owner" },
                    UserName = "admin"
                };
                rs.Message = JwtUtils.SaveToken(authInfo);
                rs.Success = true;
            }
            else
            {
                rs.Success = false;
                rs.Message = "用户名或密码不正确";
            }
            return rs;
        }
    }
}
